<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Apply;;

use App\Models\News;
use App\Models\Project;
use Illuminate\Http\Request;

class ApplyController extends BaseController
{
    public $model = Apply::class;


    public function index(Request $request) {
        $input = $request->input();
        $search = ['start_at' => '', 'end_at' => ''];
        $username = $request->input('username');
        $phone = $request->input('phone');
        $project_id = $request->input('project_id');
        $list = Apply::apply($search, $input)
            ->withCertain('project', ['name', 'company_title'])
            ->withCertain('category', ['title'])
            ->withCertain('parent_category', ['title'])
            ->when($username, function ($q) use ($username) {
                $q->where('username', 'like', '%' . $username . '%');
            })
            ->when($phone, function ($q) use ($phone) {
                $q->where('phone', 'like', '%' . $phone . '%');
            })
            ->when($project_id, function ($q) use ($project_id) {
                $q->where('project_id', $project_id);
            })
            ->orderBy("id", "desc")
            ->paginate(per_page());
        foreach ($list as $item) {
            $item->append(['ip_show']);
        }
        return $this->paginate($list);
    }


    public function store(Request $request)
    {
        $this->validate($request, [
            'username' => 'required',
            'phone' => 'required',
            'entity_id' => 'required',
            'entity_type' => 'required',
            'from' => 'required',
        ]);
        $input = $request->input();
        if ($input['entity_type'] == 'project') {
            $project = Project::find($input['entity_id']);
            if (!$project)
                return $this->failed('项目不存在');
            $input['category_id'] = $project->category_id;
            $input['parent_category_id'] = $project->parent_category_id;
            $input['project_id'] = $project->id;
            $project->apply_times += 1;
            $project->save();
        } else {
            $news = News::find($input['entity_id']);
            $project = Project::find($news->project_id);
            if (!$project)
                return $this->failed('项目不存在');
            $input['project_id'] = $project->id;
            $input['category_id'] = $project->category_id;
            $input['parent_category_id'] = $project->parent_category_id;
            $news->apply_times += 1;
            $news->save();
        }
        $input['ip'] = getip();
        unset($input['entity_id'], $input['entity_type']);
        $apply = Apply::create($input);
        return $this->success(['id' => $apply->id]);
    }


}

